﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Diagnostics;
using System.Windows.Forms;

namespace QSTOOL.Codes
{
    public class Work
    {
        public List<Command> commands { get; set; }
        public Form frmOwner { get; set; }
        private string cmdType { get; set; }

        public void Do()
        {
            foreach (Command cmd in this.commands)
            {
                switch (cmd.command)
                { 
                    case Command.DB2:
                        Command_DB2(cmd);
                        break;
                    case Command.DBF:
                    case Command.FTP:
                        break;
                    case Command.COPY:
                    case Command.DELETE:
                        break;
                }
            }
        }

        private void Command_DB2(Command cmd)
        {
            Process p = new Process();
            p.StartInfo.FileName = "db2cmd";

            //---------------TODO：替换密码和日期----------------
            p.StartInfo.Arguments = "-i -c -w " + cmd.detail + "back " + "20120827";
            p.StartInfo.UseShellExecute = false;
            p.StartInfo.RedirectStandardInput = true;
            p.StartInfo.RedirectStandardOutput = true;
            p.StartInfo.RedirectStandardError = true;
            p.StartInfo.CreateNoWindow = true;
            p.OutputDataReceived += new DataReceivedEventHandler(OutputDataReceivedHandler);
            p.Start();
            p.BeginOutputReadLine();
            
        }

        public delegate void AppendTxt(string text);

        private void OutputDataReceivedHandler(object sendingProcess, DataReceivedEventArgs outLine)
        {
            if (!String.IsNullOrEmpty(outLine.Data))
            {
                if (outLine.Data.Contains(Result.START))
                {

                }
                else if (outLine.Data.Contains(Result.COMMAND_TYPE))
                {
                    this.cmdType = outLine.Data.Substring(outLine.Data.LastIndexOf('#') + 1).Trim();
                }
                else if (outLine.Data.Contains(Result.END))
                {

                }
                else
                {
                    Result result = new Result(outLine.Data, this.cmdType);
                }

                //AppendText(outLine.Data + Environment.NewLine);
            }
        }
    }
}
